// 处理字符串相关的操作
const stringUtils = {
  /* @section 变量命名转化系列 */
  
  // 下划线命名转小驼峰命名
  snakeToCamel (name) {
    var nameArr = name.split('_')
    var len = nameArr.length
    var result = ''
    for (var i = 0; i < len; i++) {
      // 小驼峰命名法首字母不大写
      if (i == 0) {
        var section = nameArr[i]
      }
      else {
        var section = nameArr[i].substring(0, 1).toUpperCase() + nameArr[i].substring(1)
      }
      result = result + section
    }
    return result
  },
  
  // 将小驼峰命名的变量名转化为SQL的下划线命名的变量名
  camelToSnake (name) {
    return name.replace(/([A-Z])/g, '_$1').toLowerCase();
  },
  
  // 获取文件后缀名，后缀字符串包括点
  getFileTail (fileName) {
    var index = fileName.lastIndexOf('.')
    if (index >= 0) {
      return fileName.slice(index)
    }
    return ''
  },
  
  
  /*
    对于一个数字,如果位数达不到要求,在前面补0
    @prop num {String/Number} - 给定数字
    @prop limit {Number} [2] - 要求的长度
    @return {String} - 处理规范后的数字字符串
  */
  numString (num, limit = 2) {
    let result = num
    if (typeof result == 'number') {
      result = result.toString()
    }
    const delta = limit - result.length
    // 数字的长度达不到规定长度,在前面补0
    if (delta > 0) {
      for (let i = 0; i < delta; i++) {
        result = '0' + result
      }
    }
    
    return result + ''
  },
  
  // 根据时间戳获取日期字符串
  dateStrByTimestamp (stamp, endKey = 'min', sign = '-') {
    const date = new Date(stamp)
    
    const obj = {
      year: date.getFullYear(),
      month: date.getMonth() + 1,
      day: date.getDate(),
      hour: date.getHours(),
      min: date.getMinutes(),
      second: date.getSeconds()
    }
    
    return stringUtils.dateStrByObj(obj, endKey, sign)
  },
  
  dateStrByObj (obj, endKey = 'min', sign = '-') {
    const keyList = ['year', 'month', 'day', 'hour', 'min', 'second']
    let endKeyIndex = keyList.indexOf(endKey)
    endKeyIndex = endKeyIndex < 0 ? 4 : endKeyIndex
    
    let str = ''
    
    if (endKeyIndex >= 0) {
      str = str + obj.year
    }
    if (endKeyIndex >= 1) {
      str = str + sign + stringUtils.numString(obj.month)
    }
    if (endKeyIndex >= 2) {
      str = str + sign + stringUtils.numString(obj.day)
    }
    if (endKeyIndex >= 3) {
      str = str + ' ' + stringUtils.numString(obj.hour)
    }
    if (endKeyIndex >= 4) {
      str = str + ':' + stringUtils.numString(obj.min)
    }
    if (endKeyIndex >= 5) {
      str = str + ':' + stringUtils.numString(obj.second)
    }
    
    return str
  },
  
  // 获取随机字符串
  randomStr (len = 8) {
    let result = ''
    let leftLen = len
    while (leftLen > 0) {
      // 生成随即串，最多10位
      const section = Math.random().toString(36).substr(2)
      const sectionLen = section.length
      if (leftLen <= sectionLen) {
        result = result + section.substr(0, leftLen)
        leftLen = 0
      }
      else {
        result = result + section
        leftLen = leftLen - sectionLen
      }
    }
    return result
  },
  
  // 获取随机数字字符串
  randomNumStr (len = 6) {
　　let code = '';
    for (let i = 0; i < len; i++) {
      const random = Math.floor(Math.random() * 10)
      code = code + random
    }
    return code
  },
  
  // 去除字符串两边的空格
  trim (str) {
    return str.replace(/(^\s*)|(\s*$)/g, '') 
  },
  
  // 去除字符串尾部的空格
  trimTail (str) {
    return this.replace(/(\s*$)/g, '')  
  },
  
  // 去除字符串头部的空格
  trimHead (str) {
    return str.replace(/(^\s*)/g, '')  
  },
  
  // 字符串子串数量
  childStrNum (str, child) {
    return str.split(child).length - 1
  },
  
  /*
    大括号模板字符串解析.类似PHP中的字符串模板
    识别model字符串中被大括号包裹的key,用caller[key]进行替换.
    @prop model {String} - 模板字符串
    @prop caller {Object} - 替换对象
  */
  braceModel (model, caller) {
    // 正则表达式，将大括号组合提取出来
    var regExp = /\{\s*(.*?)\s*\}/g
    var resArr = model.match(regExp)
    if (!resArr) {
      return model
    }
    
    var res = model
    
    // 正则表达式，匹配开头括号和结尾括号以及中间内容两侧的空白
    var regExpContent = /(\{\s*)|(\s*\})/g
    var len = resArr.length
    for (var i = 0; i < len; i++) {
      // 提取中间的key
      var tempStr = resArr[i].replace(regExpContent, '')
      // console.log(tempStr)
      // 用.分割，获取每一层key
      var callerSearcherArr = tempStr.split('.')
      // 循环获取值，
      var replaceObj = caller
      var searcherLen = callerSearcherArr.length
      for (var j = 0; j < searcherLen; j++) {
        if (typeof replaceObj != 'undefined') {
          replaceObj = replaceObj[callerSearcherArr[j]]
        }
      }
      replaceObj = replaceObj.toString()
      res = res.replace(resArr[i], replaceObj)
    }
    
    return res  
  },
  
  // 检查字符串是不是数字字符串
  isNumberString (val) {
    if (typeof(val) === 'object' || !val) {
      return false
    }
    else {
      return !Number.isNaN(Number(val))
    }
  },
  
  // 检查字符串是否为手机号
  isPhoneNum (phone) {
    let myreg = /^[1][3,4,5,7,8][0-9]{9}$/ 
    if (!myreg.test(phone)) {
      return false
    }
    return true
  },
  
  // 对字符串中所有特殊字符进行转义，一般用于拼接正则表达式
  escapeSpecialSymbol (str) {
    const specials = ['\\', '$', '(', ')', '*', '+', '.', '[', ']', '?', '^', '{', '}', '|', '-']
    const len = specials.length
    for (let i = 0; i < len; i++) {
      str = str.replace(new RegExp('\\' + specials[i], 'g'), '\\' + specials[i])
    }
    return str
  }
}


export default stringUtils